import 'dart:io';
import 'dart:convert';
// ignore: depend_on_referenced_packages
import 'package:path/path.dart' as path;

/// file_util.dart
///
/// Created by fuchuanwei on Mon Apr 10 2023.
///
/// Description: 文件工具类
///
FileInfo getFileInfoByFile(File file) {
  String fileName = path.basename(file.path);
  String nameWithoutExtension = path.basenameWithoutExtension(file.path);
  String extension = path.extension(file.path);
  return FileInfo(
    fileName: fileName,
    nameWithoutExtension: nameWithoutExtension,
    extension: extension,
  );
}

class FileInfo {
  String? fileName;
  String? nameWithoutExtension;
  String? extension;

  FileInfo({this.fileName, this.nameWithoutExtension, this.extension});

  @override
  String toString() {
    return 'FileInfo(完整文件名称: $fileName, 文件名: $nameWithoutExtension, 文件后缀: $extension)';
  }

  factory FileInfo.fromFileNameNameWithoutExtensionExtension(
      Map<String, dynamic> data) {
    return FileInfo(
      fileName: data['fileName'] as String?,
      nameWithoutExtension: data['nameWithoutExtension'] as String?,
      extension: data['extension'] as String?,
    );
  }

  Map<String, dynamic> toFileNameNameWithoutExtensionExtension() => {
        'fileName': fileName,
        'nameWithoutExtension': nameWithoutExtension,
        'extension': extension,
      };

  /// `dart:convert`
  ///
  /// Parses the string and returns the resulting Json object as [FileInfo].
  factory FileInfo.fromJson(String data) {
    return FileInfo.fromFileNameNameWithoutExtensionExtension(
        json.decode(data) as Map<String, dynamic>);
  }

  /// `dart:convert`
  ///
  /// Converts [FileInfo] to a JSON string.
  String toJson() => json.encode(toFileNameNameWithoutExtensionExtension());
}
